package org.jcnc;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class RequestDemo {
    public static void main(String[] args) {
        registerRequest();
        loginRequest();
    }

    private static void registerRequest() {
        try {
            URL url = new URL("http://localhost:8000/register");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            String data = "username=user1&password=pass123&permission=admin";
            byte[] postData = data.getBytes(StandardCharsets.UTF_8);
            int postDataLength = postData.length;
            conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
            conn.getOutputStream().write(postData);

            int responseCode = conn.getResponseCode();
            System.out.println("Register Response Code: " + responseCode);

            if (responseCode == 200) {
                // 注册成功，执行进入新页面的逻辑
                System.out.println("Registration successful. Redirecting to new page...");
                // 进入新页面的代码
            } else {
                // 注册失败的处理逻辑
                System.out.println("Registration failed. Response Code: " + responseCode);
            }

            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void loginRequest() {
        try {
            URL url = new URL("http://localhost:8000/login");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            String data = "username=1&password=1";
            byte[] postData = data.getBytes(StandardCharsets.UTF_8);
            int postDataLength = postData.length;
            conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
            conn.getOutputStream().write(postData);

            int responseCode = conn.getResponseCode();
            System.out.println("Login Response Code: " + responseCode);

            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
